import React, { useState,useEffect, useTransition } from 'react'
import {Button, Card,Modal,Form,message,Row,Col,Input,Upload,Select,Tooltip,Divider} from 'antd'
import { useNavigate } from 'react-router-dom';
import useCacheAlive from '@/hooks/useCacheAlive'
import MemoTable from '@/components/MemoTable';
import { useTranslation } from 'react-i18next';
import { UploadOutlined } from '@ant-design/icons';  
import {download} from '@/utils/request';
import { list,del,add,edit,importInciList} from "@/api/modules/tspec2015";
import { upload } from "@/api/modules/common";
import { ProFormColumnsType } from '@ant-design/pro-components'
import Children from './listinci'
import { getInfo } from "@/api/login/ssoLogin";



const tspec2015 = () => {
  const navigate = useNavigate();
  const { t } = useTranslation()
  const [isModalVisible, setIsModalVisible] = useState(false); 
  const [Title, setTitle] = useState("")  
  const [form] = Form.useForm();  
  const [fileList, setFileList] = useState([]); 
  const [annex, setAnnex] = useState(""); 
  const [serial, setSerial] = useState("");
  const [productTypeBodyPart, setProductTypeBodyPart] = useState("");
  const [isView, SetisView] = useState(false)
  const [onReloadNum, setReloadNum] = useState(null); 
  const [isModalINCIVisible, setIsModalINCIVisible] = useState(false);
  const [isModalVisibleUpload, setIsModalVisibleUpload] = useState(false);  
  const [loading, setLoading] = useState(false); // 加载状态 
  const [viewStatus, setViewStatus] = useState(false); // 加载状态 


  // 使用useEffect在组件挂载时获取数据  
  useEffect(() => {  
    getInfo().then(res=>{
      console.log(res,'res')
      let data = res.data
      data.roles.forEach((item)=>{
        if(item == "Formulator"){
          setViewStatus(true)
        }
      })
    }) 

  }, []);

  const formColumns:ProFormColumnsType[] = [{
    title: t('Ingredient'),
    dataIndex: 'search',
    valueType: 'text', 
  },{
    title:'INCI',
    dataIndex: 'inci',
    valueType: 'text', 
  },  {  
    title: t('VendorType.type'),  
    dataIndex: 'annex', // 假设这是select绑定的字段名  
    valueType: 'select', // 字段类型  
    valueEnum: {
      '限用组分': { text: '限用组分', status: '限用组分' },
      '准用防腐剂': { text: '准用防腐剂', status: '准用防腐剂' },
      '准用着色剂': { text: '准用着色剂', status: '准用着色剂' },
      '准用染发剂': { text: '准用染发剂', status: '准用染发剂' },
      '准用防晒剂': { text: '准用防晒剂', status: '准用防晒剂' },
    },
  },  ]

  const columns: any = [
    {
      title: t('tspec2015.annex'),
      dataIndex: 'annex',
      key: 'annex',
      width: 80,
      fixed:'left',
      ellipsis: {
        showTitle: false,
      },
      render: (annex) => (
        <Tooltip placement="topLeft" title={annex}>
          {annex}
        </Tooltip>
      ),
    },
    {
      title: t('tspec2015.serial'),
      dataIndex: 'serial',
      width: 100,
      key: 'serial',
      ellipsis: {
        showTitle: false,
      },
      render: (serial) => (
        <Tooltip placement="topLeft" title={serial}>
          {serial}
        </Tooltip>
      ),
    },
    {
      title: t('tspec2015.chemicalNameCn'),
      dataIndex: 'chemicalNameCn',
      width: 120,
      key: 'chemicalNameCn',
      ellipsis: {
        showTitle: false,
      },
      render: (chemicalNameCn) => (
        <Tooltip placement="topLeft" title={chemicalNameCn}>
          {chemicalNameCn}
        </Tooltip>
      ),
    },
    {
      title: t('tspec2015.chemicalNameEn'),
      dataIndex: 'chemicalNameEn',
      width: 80,
      key: 'chemicalNameEn',
      ellipsis: {
        showTitle: false,
      },
      render: (chemicalNameEn) => (
        <Tooltip placement="topLeft" title={chemicalNameEn}>
          {chemicalNameEn}
        </Tooltip>
      ),
    },
    {
      title: t('tspec2015.productTypeBodyPart'),
      dataIndex: 'productTypeBodyPart',
      key: 'productTypeBodyPart',
      ellipsis: {
        showTitle: false,
      },
      render: (productTypeBodyPart) => (
        <Tooltip placement="topLeft" title={productTypeBodyPart}>
          {productTypeBodyPart}
        </Tooltip>
      ),
    },
    {
      title: t('tspec2015.maxConcentration'),
      dataIndex: 'maxConcentration',
      key: 'maxConcentration',
      ellipsis: {
        showTitle: false,
      },
      render: (maxConcentration) => (
        <Tooltip placement="topLeft" title={maxConcentration}>
          {maxConcentration}
        </Tooltip>
      ),
    },
    {
      title: t('tspec2015.other'),
      dataIndex: 'other',
      key: 'other',
      width:120,
      ellipsis: {
        showTitle: false,
      },
      render: (other) => (
        <Tooltip placement="topLeft" title={other}>
          {other}
        </Tooltip>
      ),
    },
    {
      title: t('tspec2015.wordConditionUseWarning'),
      dataIndex: 'wordConditionUseWarning',
      key: 'wordConditionUseWarning',
      ellipsis: {
        showTitle: false,
      },
      render: (wordConditionUseWarning) => (
        <Tooltip placement="topLeft" title={wordConditionUseWarning}>
          {wordConditionUseWarning}
        </Tooltip>
      ),
    },
    {
      title: t('tspec2015.color'),
      dataIndex: 'color',
      key: 'color',
      width:80,
      ellipsis: {
        showTitle: false,
      },
      render: (color) => (
        <Tooltip placement="topLeft" title={color}>
          {color}
        </Tooltip>
      ),
    },
    {
      title: t('tspec2015.annexDetailDesc'),
      dataIndex: 'annexDetailDesc',
      key: 'annexDetailDesc',
      ellipsis: {
        showTitle: false,
      },
      render: (annexDetailDesc) => (
        <Tooltip placement="topLeft" title={annexDetailDesc}>
          {annexDetailDesc}
        </Tooltip>
      ),
    },
    {  
      title: t('action'),  
      key: 'action',
      fixed:'right',
      render: (text, record) => (  
        <>  
           <Button type="link"  onClick={() => handleInci(record)}>  
           {t('tspec2015.IngredientInformation')}  
          </Button> 
           <Button type="link"  onClick={() => handleView(record)}>  
           {t('view')}  
          </Button> 
          {viewStatus ? null : (
            <>
              <Button type="link" onClick={() => handleEdit(record)}>
                {t('edit')}
              </Button>
              <Button type="link" danger onClick={() => handleDelete(record.id)}>
                {t('delete')}
              </Button>
            </>
          )}
   
        </>  
      ),  
    },  
  ];



  const getData = async (formData) => {
    const { success, data} = await list({...formData, orderby: 'id', order: 0})
    if(!success) return false
    console.log(data)
    const list2 = data.data.page
    return {
      data: list2,
      total: data.data.total
    }
  } 

  const handleAdd = () =>{
    SetisView(false)
    form.resetFields()
    setTitle("新增/New")
    showModal()
  }

  const showModal = () => {  
    setIsModalVisible(true);  
  };  

  
  const handleOk = () => {  
    // 调用接口添加数据，这里假设你有一个函数addFormData来处理添加逻辑  
    // const response = addFormData(newFormData);  
    // ...处理接口响应...  
    const values = form.getFieldsValue();  
    if(Title=='新增/New'){
        //新增
        values.id =null
        add(values).then(res=>{
            message.success("Success")
            setReloadNum(Date.now())
             // 假设添加成功，关闭弹窗  
            setIsModalVisible(false);  
        }).catch(()=>{
           
        })
    }else{
        //修改
        edit(values).then(res=>{
            message.success("Success")
            setReloadNum(Date.now())
             // 假设添加成功，关闭弹窗  
            setIsModalVisible(false);  
        }).catch(()=>{
       })
    }

  
    // 根据需要更新formData或执行其他逻辑  
    // ...  
  };  

  const handleInci = (record) =>{
    console.log('编辑当前行数据：', record);
    const serial = record.serial;  
    const annex = record.annex
    setSerial(record.serial)
    setAnnex(record.annex)
    setProductTypeBodyPart(record.productTypeBodyPart)
    setIsModalINCIVisible(true)
    // 跳转到'/sa/addreport'路径，并带上id参数  
    // navigate(`/safety/children?serial=${serial}&annex=${annex}`); 
    
  }

  const handleView = (record) =>{
   SetisView(true)
   setTitle("查看/View")
   console.log(record,'record')
   form.setFieldsValue({ ...record });  
   setIsModalVisible(true);  
  }

  const handleEdit = (record) =>{
    SetisView(false)
    setTitle("修改/Edit")
    console.log(record,'record')
    form.setFieldsValue({ ...record });  
    setIsModalVisible(true);  
    // 这里可以添加打开模态框并显示编辑表单的逻辑  
  }

  const handleDelete = (key) =>{
    let inciIds = []
    inciIds.push(key)
    Modal.confirm({  
      title: 'Confirm Delete',  
      content: 'Please confirm to DELETE SELECTED RECORDS!',  
      onOk() {  
        del(inciIds).then(res=>{
            message.success("Success")
            setReloadNum(Date.now())
        }) 
      },  
    }); 
  }

  const handleINCICancel = () => {  
    setIsModalINCIVisible(false);  
  };  
  
  const handleCancel = () => {  
    setIsModalVisible(false);  
  };  

  
  const showModal2 = () => {  
    setIsModalVisibleUpload(true);  
  };  

  
  const handleCancel2 = () => {  
    setIsModalVisibleUpload(false);  
  }; 

  const handleDownload = () => {  
    // 这里可以添加处理下载操作的逻辑，比如调用下载接口  
    download("/api/incigroup/exportInciListTemplate", {
      
    }, `Inci List Template.xlsx`);
  };  

  const handleFileChange = (info) => { 
    console.log(info,'info')
    info.file.status = "done"
    if(info.fileList.length==0){

    }else{
      setLoading(true);
      const files = info.fileList[0].originFileObj
        let formData = new FormData();
        formData.append("file", files);
        importInciList(formData).then(response=>{
          if (response.data.status == 0) {
              message.success("Success")
              setIsModalVisibleUpload(false)
              setLoading(false);
          }else{
         let message1 = ""
         message1 += response.data.message+'<br/>'
         response.data.data.map(i=>{
            message1 += i+' <br/>'
         })
         message.error(message1)
         setLoading(false);
         setIsModalVisibleUpload(false)
          }
          }).catch(()=>{
            setLoading(false);
            setIsModalVisibleUpload(false)
          })
    }
  };  

  const renderOperator = <>
    <Button disabled={viewStatus} type="primary" size="small" onClick={handleAdd}>{t('add')}</Button>
    <Button disabled={viewStatus} style={{marginLeft:'1%'}} size="small" type="primary" onClick={showModal2}>  
          {t('tspec2015.INCIImport')}  
        </Button> 
  </>
  
  return (
    <div> 
    <MemoTable 
      name='basic'
      formColumns={formColumns}
      columns={columns as any}
      rowKey='id'
      operator={renderOperator}
      getData={getData}
      refreshKey={onReloadNum}
    />
    <Modal  
          title={Title}
          visible={isModalVisible}  
          onOk={handleOk}  
          onCancel={handleCancel}  
        >  
          <Form form={form} layout="vertical">
            <Form.Item  
                name="id"  
                label="id" 
                hidden 
            >  
                <Input disabled/>  
            </Form.Item> 
            {/* 这里假设添加的内容也是一个对象，包含key和value */}  
            <Form.Item  
              name="annex"  
              label={t('tspec2015.annex')}
              rules={[{ required: true, message: '请输入附表！' }]}    
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="serial"  
              label={t('tspec2015.serial')}
              rules={[{ required: true, message: '请输入序号！' }]}    
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="chemicalNameCn"  
              label={t('tspec2015.chemicalNameCn')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="chemicalNameEn"  
              label={t('tspec2015.chemicalNameEn')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="productTypeBodyPart"  
              label={t('tspec2015.productTypeBodyPart')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="maxConcentration"  
              label={t('tspec2015.maxConcentration')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>
            <Form.Item  
              name="other"  
              label={t('tspec2015.other')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="wordConditionUseWarning"  
              label={t('tspec2015.wordConditionUseWarning')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="color"  
              label={t('tspec2015.color')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="annexDetailDesc"  
              label={t('tspec2015.annexDetailDesc')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
          </Form>  
        </Modal> 
        <Modal  
          title="INCI"
          visible={isModalINCIVisible}  
          onCancel={handleINCICancel} 
          width={1000}
          footer={[  
            <Button key="back" onClick={handleINCICancel}>  
              {t('cancel')}  
            </Button>,  
          ]}  
        >  
           <Children oldannex={annex} oldserial={serial} oldproduct={productTypeBodyPart}></Children>
        </Modal> 
        <Modal  
        title="INCI List Import"  
        visible={isModalVisibleUpload}  
        onCancel={handleCancel2} 
        destroyOnClose 
        footer={null} // 隐藏默认的footer  
      >  
        <div style={{ marginBottom: '16px' }}>  
          <Button type="primary" onClick={handleDownload}>  
            {t('report.templateDownload')}  
          </Button>  
        </div>  
        <p style={{ color: 'red', fontSize: '12px' }}>*{t('tspec2015.inciUpload')}</p>  
        <Divider style={{ marginBottom: '16px' }} />  
        <Upload  
                customRequest={({ file, onSuccess, onError }) => {  
                  // 这里是自定义上传逻辑，您可以根据实际需求实现上传逻辑  
                  // 例如，使用axios发送POST请求上传文件  
                  // 注意：这里的逻辑与表单提交时的文件上传是独立的，如果只需要在表单提交时上传，可以省略这部分  
                }}  
                onChange={handleFileChange} 
              >  
                <Button icon={<UploadOutlined />}>{t('selectUpload')}</Button>  
              </Upload> 
      </Modal> 
    </div>
  )
}
export default tspec2015
